renderStudentList()//渲染学生管理列表
initcitySelect()//初始化省市区



const tbody = document.querySelector('tbody');
const model = new bootstrap.Modal('.modal')//模态框显示隐藏
// const modalBootstrap = new bootstrap.Modal('.modal')
const showModalBtn = document.querySelector('.show-modal-btn');//添加学员按钮
const addForm = document.querySelector('.add-form');
const province = document.querySelector('[name="province"]');//省
const city = document.querySelector('[name="city"]');//市
const county = document.querySelector('[name="county"]');//区

//渲染学生管理列表
async function renderStudentList() {
    const refult = await axios({ url: '/student/list' })
    // console.log(refult);
    const html = refult.data.reduce((a, { id, name, age, sex, group, phone, salary, truesalary, province, city, county }) => a + `<tr>
   <th scope="row">${id}</th>
   <td>${name}</td>
   <td>${age}</td>
   <td>${sex}</td>
   <td>${group}</td>
   <td>${phone}</td>
   <td>${salary}</td>
   <td>${truesalary}</td>
   <td>${province + city + county}</td>
   <td>
     <button type="button" class="btn btn-primary btn-sm" data-id=${id}>修改</button>
     <button type="button" class="btn btn-danger btn-sm" data-id=${id}>删除</button>
   </td>
 </tr>`, '')
    tbody.innerHTML = html
}

//点击添加学员按钮事件
showModalBtn.addEventListener('click', function (e) {
    model.show()
    document.querySelector('#addModalLabel').innerText = '录入新学员'
    addForm.reset()//重置表单
})
//重置地区
addForm.addEventListener('reset', function (e) {
    city.innerHTML = '<option value="">--市--</option>'
    county.innerHTML = '<option value="">--区--</option>'
})

//初始化省市区
async function initcitySelect() {
    const result = await axios({ url: '/geo/province' })
    province.innerHTML = result.reduce((a, b) => a + `<option value=${b}>${b}</option>`, '<option value="">--省--</option>')

    province.addEventListener('change', async function (e) {
        const result = await axios({ url: '/geo/city', params: { pname: province.value } })
        city.innerHTML = result.reduce((a, b) => a + `<option value=${b}>${b}</option>`, '<option value="">--市--</option>')
        //重置地区
        county.innerHTML = '<option value="">--区--</option>'
    })

    city.addEventListener('change', async function (e) {
        const result = await axios({ url: '/geo/county', params: { pname: province.value, cname: city.value } })
        county.innerHTML = result.reduce((a, b) => a + `<option value=${b}>${b}</option>`, '<option value="">--区--</option>')
    })
}

//添加学员
addForm.addEventListener('submit', async function (e) {
    e.preventDefault()
    const data = serialize(addForm, { hash: true, empty: true })
    const { id } = data//获取编辑数据的id
    delete data.id

    // for (const key in data) {
    //     if (!data[key]) {
    //         toastr.error('表单不能为空')
    //         return
    //     }
    // }
    if (!/[a-zA-Z0-9\u4e00-\u9fa5]{2,10}/.test(data.name)) {
        toastr.error('姓名，2~10位')
        return
    }
    if (data.sex !== '男' && data.sex !== '女') {
        toastr.error('性别，男或女，不得填写其他值')
        return
    }
    if (!/[0-9]{1,2}/.test(data.age)) {
        toastr.error('年龄，1-2位数字')
        return
    }
    if (!/[0-9]{1,2}/.test(data.group)) {
        toastr.error('组号，1~2位数字')
        return /^[1][3-9][0-9]{9}$/
    }
    if (!/^[1][3-9][0-9]{9}$/.test(data.phone)) {
        toastr.error('手机号，11位数字')
        return
    }
    if (!/^[1-9]\d{2,4}$/.test(data.salary)) {
        toastr.error('期望薪资，100到99999')
        return
    }
    if (!/^[1-9]\d{2,4}$/.test(data.truesalary)) {
        toastr.error('实际薪资，100到99999')
        return
    }

    let method = ''
    let url = ''
    if (document.querySelector('#addModalLabel').innerText === '录入新学员') {
        method = 'post'
        url = '/student/add'
    } else {
        data.id = id
        method = 'put',
            url = 'student/update'
    }

    const result = await axios({
        method,
        url,
        data
    })
    toastr.success('操作成功')
    addForm.reset()
    model.hide()
    renderStudentList()
})


//操作列表
tbody.addEventListener('click', async function (e) {
    // 删除学员
    if (e.target.classList.contains('btn-danger')) {
        const { id } = e.target.dataset
        if (confirm('您确认删除吗？')) {
            const result = await axios({
                method: 'delete',
                url: `/student/delete`,
                params: { id: id }
            })
            toastr.success(result.message)
            renderStudentList()
        }
    }

    //修改学员信息
    if (e.target.classList.contains('btn-primary')) {
        model.show()
        document.querySelector('#addModalLabel').innerText = '修改学员信息'
        const { id } = e.target.dataset
        const result = await axios({
            url: '/student/one',
            params: {
                id: id
            }
        })
        console.log(result);
        //回填单选框
        document.querySelector(`[name="sex"][value=${result.data.sex}]`).checked = true

        //初始地市区，方便回填地市区的下拉列表
        const cityResult = await axios({ url: '/geo/city', params: { pname: result.data.province } })
        city.innerHTML = cityResult.reduce((a, b) => a + `<option value=${b}>${b}</option>`, '<option value="">--市--</option>')
        const countyResult = await axios({ url: '/geo/county', params: { pname: result.data.province, cname: result.data.city } })
        county.innerHTML = countyResult.reduce((a, b) => a + `<option value=${b}>${b}</option>`, '<option value="">--区--</option>')

        //回填表单
        const formData = addForm.querySelectorAll('[name]');
        formData.forEach(v => {
            if (v.name !== 'sex') {
                v.value = result.data[v.name]
            }
        })

    }

})


